package com.wenjie.service.impl;

import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.core.row.Db;
import com.mybatisflex.core.row.Row;
import com.wenjie.original.entity.SysCodeTempGroup;
import com.wenjie.original.entity.common.vo.RestBaseVo;
import com.wenjie.original.entity.table.SysCodeTempTableDef;
import com.wenjie.original.entity.vo.SysCodeTemp.SysCodeTempVo;
import com.wenjie.original.service.ISysCodeTempGroupService;
import com.wenjie.original.service.ISysCodeTempService;
import com.wenjie.service.ICodeTemplateHandle;
import com.wenjie.service.IGenService;
import com.wenjie.vo.gen.TableInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class GenService implements IGenService {

    @Autowired
    private ICodeTemplateHandle codeTemplateHandle;

    @Autowired
    private ISysCodeTempService sysCodeTempService;

    @Autowired
    private ISysCodeTempGroupService sysCodeTempGroupService;


    @Override
    public RestBaseVo<TableInfo> getTables() {
        RestBaseVo<TableInfo> restBaseVo = new RestBaseVo<>();
        List<Row> rows = Db.selectListBySql("SHOW TABLE STATUS;");

        List<TableInfo> tableInfos = new ArrayList<>();
        for (Row row : rows) {
            TableInfo entity = row.toEntity(TableInfo.class);
            tableInfos.add(entity);
        }
        restBaseVo.setList(tableInfos);
        restBaseVo.setMax(Long.valueOf(tableInfos.size()));
        return restBaseVo;
    }

    @Override
    public String showStructure(String name) {
        Row row = Db.selectOneBySql("show CREATE TABLE " + name + ";");
        return row.getString("Create Table");
    }

    @Override
    public RestBaseVo<SysCodeTempVo.ResVo> genGroup(String name, Long codeTemplateId) {

        // 获取代码组的自定义信息
        SysCodeTempGroup sysCodeTempGroup = sysCodeTempGroupService.getById(codeTemplateId);

        // 获取全部的代码模版
        RestBaseVo<SysCodeTempVo.ResVo> rest = sysCodeTempService.list(QueryWrapper.create().where(SysCodeTempTableDef.SYS_CODE_TEMP.SYS_CODE_TEMP_GROUP_ID.eq(codeTemplateId)), SysCodeTempVo.ResVo.class);

        for (SysCodeTempVo.ResVo resVo : rest.getList()) {
            resVo.setGenValue(codeTemplateHandle.exeDetail(name, resVo.getValue(), sysCodeTempGroup.getCusParam()));
            resVo.setGenFileName(codeTemplateHandle.exeDetail(name, resVo.getFileName(), sysCodeTempGroup.getCusParam()));
        }
        return rest;
    }
}
